package com.cloud.api.game.controller;

import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cloud.api.base.BaseController;
import com.cloud.api.game.service.GameService;
import com.cloud.common.core.BMDataContext;
import com.cloud.common.result.ExecuteResult;
import com.cloud.model.GameData;
import com.cloud.model.GamePlayway;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;

@RestController
@RequestMapping("/game")
public class GameController extends BaseController {
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private GameService gameService;

	/**
	 * 得到游戏配置
	 * 
	 * @param requestHeader
	 * @return
	 */
	@GetMapping("/config")
	public Mono<ExecuteResult<GameData>> gameconfig() {
		try {
			String orgi = BMDataContext.SYSTEM_ORGI;
			return gameService.getGameData(orgi).map(data -> {
//				logger.info("data is {}", data);
				return ExecuteResult.ok(data);
			});
		} catch (Exception e) {
			logger.error("游客登录失败", e);
			return Mono.just(ExecuteResult.fail("游客登录失败！"));
		}
	}

//	@GetMapping(value = "/gamePlayway")
	@GetMapping(value = "/gamePlayway", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
	public Flux<GamePlayway> findGamePlayway() {
		String orgi = BMDataContext.SYSTEM_ORGI;
		return gameService.findGamePlayway(orgi);
	}
	
	@GetMapping(value = "/randomNumbers")
    public Flux<ServerSentEvent<GameData>> randomNumbers() {
		GameData gameData = new GameData();
        return Flux.interval(Duration.ofSeconds(1))
                .map(seq -> Tuples.of(seq, ThreadLocalRandom.current().nextInt()))
                .map(data -> {
                	gameData.setOrgi(Integer.toString(data.getT2()));
                	ServerSentEvent<GameData> result = ServerSentEvent.<GameData>builder()
                        .event("random")
                        .id(Long.toString(data.getT1()))
                        .data(gameData)
                        .build();
                	return result;
                });
    }

}